/*
 * Copyright 2012 Finbudget.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package finbudgettable.client.ui.grid.cell;

import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.PopupPanel;

public abstract class AbstractPopupEditor<C> extends PopupPanel {

    private Element lastParent;
    private HandlerRegistration closeHandlerRegistration;
    private boolean readonly;

    public abstract void setValue(C value);
    public abstract void proceedSettingReadonly();

    public AbstractPopupEditor() {
        super(true, true);
    }

    public AbstractPopupEditor(boolean autoHide, boolean modal) {
        super(autoHide, modal);
    }

    protected void onPreviewNativeEvent(Event.NativePreviewEvent event) {
        if (Event.ONKEYUP == event.getTypeInt()) {
            int keyCode = event.getNativeEvent().getKeyCode();
            if (keyCode == KeyCodes.KEY_ESCAPE) {
                hide();
            } else if (keyCode == KeyCodes.KEY_TAB) {
                hide();
            }
        }
    }

    public void setParent(Element lastParent) {
        this.lastParent = lastParent;
    }

    public Element getLastParent() {
        return lastParent;
    }

    @Override
    protected void onLoad() {
        super.onLoad();
        closeHandlerRegistration = Window.addResizeHandler(new ResizeHandler() {
            @Override
            public void onResize(ResizeEvent event) {
                if (isVisible()) {
                    hide(true);
                }
            }
        });
    }

    @Override
    protected void onUnload() {
        super.onUnload();
        if (closeHandlerRegistration != null) {
        	closeHandlerRegistration.removeHandler();
        	closeHandlerRegistration = null;
        }
    }

    public void setReadOnly(boolean readonly) {
    	this.readonly = readonly;
    	proceedSettingReadonly();
    }

    public boolean isReadonly() {
        return readonly;
    }

}
